using System;
using System.Data;
using System.Data.SQLite;

namespace Rioshu.Web.ViewStateHandlers.SQLitePersister
{
    public class SqliteViewStateManager
    {
        const string InsertCmd = "INSERT INTO viewstate (id, data) VALUES (@id, @data)";
        const string SelectCmd = "SELECT data FROM viewstate WHERE id = @id";

        const string TableCmd =
            "CREATE TABLE IF NOT EXISTS viewstate (id GUID PRIMARY KEY, data BLOB NOT NULL, added DATETIME NOT NULL DEFAULT DATETIME())";

        static readonly SqlitePersisterConfiguration Configuration = SqlitePersisterConfiguration.GetConfiguration();

        public static Guid SaveState(byte[] viewstate)
        {
            CheckDatabaseSchema();

            Guid guid = Guid.NewGuid();
            var cmd = new SQLiteCommand(InsertCmd)
                {
                    Connection = SqliteConnectionManager.GetConnection()
                };

            cmd.Parameters.Add("@id", DbType.Guid).Value = guid;
            cmd.Parameters.Add("@data", DbType.Binary, viewstate.Length).Value = viewstate;

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            return guid;
        }

        static void CheckDatabaseSchema()
        {
            if (!SQLiteMetaDataCollectionNames.Tables.Contains("viewstate")) CreateDatabaseSchema();
        }

        static void CreateDatabaseSchema()
        {
            var cmd = new SQLiteCommand(TableCmd, SqliteConnectionManager.GetConnection());
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
        }

        public static byte[] LoadState(Guid id)
        {
            var cmd = new SQLiteCommand(SelectCmd)
                {
                    Connection = SqliteConnectionManager.GetConnection()
                };

            cmd.Parameters.Add("@id", DbType.Guid).Value = id;

            cmd.Connection.Open();
            var result = (byte[]) cmd.ExecuteScalar();
            cmd.Connection.Close();

            return result;
        }
    }
}